﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using XJay.Identity.Common.CustomException;
using XJay.Identity.Model;
using XJay.Identity.Model.Enums;

namespace XJay.Identity.Middleware
{
    public class AppExceptionHandler : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {

            //判断该异常有没有处理
            if (context.ExceptionHandled)
            {
                return;
            }
            ResposeData resposeData = new ResposeData()
            {
                Msg = context.Exception.Message
            };
            if (context.Exception is ArgumentNullException)
            {
                resposeData.Code = (int)ExceptionCodeEnum.ArgumentNull;
            }
            else if (context.Exception is XJayException)
            {
                resposeData.Code = (int)ExceptionCodeEnum.XJay;
            }
            else
            {
                resposeData.Code = (int)ExceptionCodeEnum.Accident;
                resposeData.Msg = "Server exception";
            }

            context.Result = new JsonResult(resposeData);
            //标记异常已处理
            context.ExceptionHandled = true;
        }
    }
}
